package org.sraosha.framework.helper;

import com.alibaba.fastjson.JSON;
import org.sraosha.framework.dto.ApiResult;
import org.sraosha.framework.enumeration.ApiResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.shaded.com.google.common.base.Charsets;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class InterceptorHelper {

    public void response(HttpServletResponse httpServletResponse, ApiResultEnum apiResultEnum){
        try {
            // 使用response获得字节输出
            httpServletResponse.setCharacterEncoding(Charsets.UTF_8.toString());
            PrintWriter printWriter = httpServletResponse.getWriter();
            log.warn(apiResultEnum.getMessage());
            ApiResult apiResult = ApiResult.error(apiResultEnum.getCode(), apiResultEnum.getMessage());
            String json = JSON.toJSONString(apiResult);
            printWriter.write(json);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
